package com.fyyg.monitor.util;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 账户锁
 *
 * @author hang.ouyang
 * @date 2016-04-16 9:39
 */
public class AccountLock {

    private static Map<String, Lock> accounts = new HashMap<String, Lock>();
    private static Lock lock = new ReentrantLock();
    private AccountLock() { }


    public static Lock lockMember(Integer uid){
        return lockObject("member"+uid);
    }

    public static Lock lockProductGroup(Integer groupId){
        return lockObject("productGroup"+groupId);
    }

    public static Lock lockOrderBatch(Integer batchId){
        return lockObject("orderBatch"+batchId);
    }

    public static Lock lockOrderBatch(String batchNo){
        return lockObject("orderBatch"+batchNo);
    }

    public static Lock lockProduct(Integer productId){
        return lockObject("product"+productId);
    }
    public static Lock lockAssistant(Integer assistantId){
        return lockObject("assistant"+assistantId);
    }

    /**
     * 通过传对象ID,来对该对象进行同步锁
     * @param key 对象ID
     * @return  用来进行同步的对象
     */
    private static Lock lockObject(String key) {
        try {
            lock.lock();
            Lock tempLock = accounts.get(key);
            if (null == tempLock) {
                tempLock =  new ReentrantLock();
                accounts.put(key, tempLock);
            }
            return tempLock;
        } finally {
            lock.unlock();
        }
    }
}
